package com.sunxueqi.common.utils;

import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import com.sunxueqi.common.exception.CustomException;
import com.sunxueqi.framework.security.LoginUser;

public class SecurityUtils {

	/**
     * 获取Authentication
     */
	public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
	
	/**
	 * 获取登录用户信息
	 */
	public static LoginUser getLoginUser() {
		try {
			return (LoginUser)getAuthentication().getPrincipal();
		} catch (Exception e) {
			//throw new CustomException("获取登录用户信息异常", HttpStatus.UNAUTHORIZED);
			return null;
		}
	}
	
	/**
	 * 获取登录用户id
	 */
	public static String getLoginUserId() {
		try {
			return getLoginUser().getUser().getId();
		} catch (Exception e) {
			throw new CustomException("获取登录用户信息异常", HttpStatus.UNAUTHORIZED);
		}
	}
	
	/**
	 * 获取登录用户账号
	 */
	public static String getLoginUsername() {
		try {
			return getLoginUser().getUsername();
		} catch (Exception e) {
			throw new CustomException("获取登录用户账号异常", HttpStatus.UNAUTHORIZED);
		}
	}
	
	/**
	 * 判断当前用户是不是管理员
	 * @return 是管理员则返回true，否则返回false
	 */
	public static boolean isAdmin() {
		try {
			LoginUser loginUser = getLoginUser();
			return loginUser.getUser().isAdmin();
		} catch (Exception e) {
			return false;
		}
	}
	
    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }
    
    public static void main(String[] args) {
        System.out.println(encryptPassword("admin"));
    }
    
    
}
